package com.z.utils;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
/**
 * http 工具
 * @author 1340105413@qq.com
 *
 */
public class Utils {
	private static HttpGet hget = null;
	private static HttpClient hClient = null;

	public static Document getDocument(String url) {
		// 创建httpClient客户端
		Document document=null;
		hClient = new DefaultHttpClient();
		hClient.getParams()
				.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)
				.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
		// 创建http发送请求对象，Httpget
		hget = new HttpGet(url);
		hget.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0");
		// 发送请求
		HttpResponse response = null;
		try {
			response = hClient.execute(hget);
			String content = EntityUtils.toString(response.getEntity(), "utf-8");
			document=Jsoup.parse(content);
		} catch (java.net.ConnectException e) {
			System.out.println(e.getMessage() + "::正在重连。。");
			return getDocument(url);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (response == null)
				return null;
		}
		return document;
	}
}
